package org.deng.learn.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
 * @author 邓力宾
 * @Desc
 * @since 2020/6/15 下午1:57
 */
public class MyServerHandler  extends ChannelInboundHandlerAdapter{
    /*
     * 收到消息时，返回信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务端接受的消息 : " + msg.toString());
        if("quit".equals(msg)){//服务端断开的条件
            ctx.close();
        }
        // 返回客户端消息
        ctx.writeAndFlush("hello client from server\n"); //  \n不能少
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        System.out.println("通道读取完成");
        ctx.flush();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
    /*
     * 建立连接时，返回消息
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }
}
